 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=62 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Generate random numbers
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='pitfall,random,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Generate random numbers</div>

<div class='main-body'>
 
There are two means of generating random (really pseudo-random) numbers :
<ul>
<li>the <tt><a href="http://java.sun.com/javase/6/docs/api/java/util/Random.html">Random</a></tt> class generates 
random integers, doubles, longs and so on, in various ranges.
<li>the static method <tt>Math.<a href="http://java.sun.com/javase/6/docs/api/java/lang/Math.html#random()">random</a></tt>
generates <em>doubles</em> between 0 (inclusive) and 1 (exclusive).
</ul>

To generate random <em>integers</em> :
<ul>
<li>do not use <tt>Math.<a href="http://java.sun.com/javase/6/docs/api/java/lang/Math.html#random()">random</a></tt>
(it produces doubles, not integers)</li>

<li>use the <tt><a href="http://java.sun.com/javase/6/docs/api/java/util/Random.html">Random</a></tt>
class to generate random integers between 0 and N.

</ul>

<P>To generate a series of random numbers as a unit, you need to use a <em>single</em>
<tt>Random</tt> object - do <em>not</em> create a new <tt>Random</tt> object for each new random
number.

See also the related Sun <a href="http://developer.java.sun.com/developer/TechTips/2000/tt1107.html" title='Has Oracle removed Tech Tips?'>Tech
Tip.</a>

<p>Another alternative is <tt><a href="http://java.sun.com/javase/6/docs/api/java/security/SecureRandom.html">SecureRandom</a></tt>,
a cryptographically strong subclass of <tt>Random</tt>.

<p><b>Example 1</b>
<br>
<PRE>

<span class='keyword'>import</span> java.util.Random;

<span class='comment'>/** Generate 10 random integers in the range 0..99. */</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> RandomInteger {
  
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>final</span> <span class='keyword'>void</span> main(String... aArgs){
    log(<span class='literal'>"Generating 10 random integers in range 0..99."</span>);
    
    <span class='comment'>//note a single Random object is reused here
</span>    Random randomGenerator = <span class='keyword'>new</span> Random();
    <span class='keyword'>for</span> (<span class='keyword'>int</span> idx = <span class='literal'>1</span>; idx <= <span class='literal'>10</span>; ++idx){
      <span class='keyword'>int</span> randomInt = randomGenerator.nextInt(<span class='literal'>100</span>);
      log(<span class='literal'>"Generated : "</span> + randomInt);
    }
    
    log(<span class='literal'>"Done."</span>);
  }
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> log(String aMessage){
    System.out.println(aMessage);
  }
}
 
</PRE>
<br>
Example run of this class :
<PRE>
Generating 10 random integers in range 0..99.
Generated : 44
Generated : 81
Generated : 69
Generated : 31
Generated : 10
Generated : 64
Generated : 74
Generated : 57
Generated : 56
Generated : 93
Done.
</PRE>

<p><b>Example 2</b>
<P>This example generates random integers in a specific range.
<br>
<PRE>

<span class='keyword'>import</span> java.util.Random;

<span class='comment'>/** Generate random integers in a certain range. */</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> RandomRange {
  
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>final</span> <span class='keyword'>void</span> main(String... aArgs){
    log(<span class='literal'>"Generating random integers in the range 1..10."</span>);
    
    <span class='keyword'>int</span> START = <span class='literal'>1</span>;
    <span class='keyword'>int</span> END = <span class='literal'>10</span>;
    Random random = <span class='keyword'>new</span> Random();
    <span class='keyword'>for</span> (<span class='keyword'>int</span> idx = <span class='literal'>1</span>; idx <= <span class='literal'>10</span>; ++idx){
      showRandomInteger(START, END, random);
    }
    
    log(<span class='literal'>"Done."</span>);
  }
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> showRandomInteger(<span class='keyword'>int</span> aStart, <span class='keyword'>int</span> aEnd, Random aRandom){
    <span class='keyword'>if</span> ( aStart &gt; aEnd ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Start cannot exceed End."</span>);
    }
    <span class='comment'>//get the range, casting to long to avoid overflow problems
</span>    <span class='keyword'>long</span> range = (<span class='keyword'>long</span>)aEnd - (<span class='keyword'>long</span>)aStart + <span class='literal'>1</span>;
    <span class='comment'>// compute a fraction of the range, 0 &lt;= frac &lt; range
</span>    <span class='keyword'>long</span> fraction = (<span class='keyword'>long</span>)(range * aRandom.nextDouble());
    <span class='keyword'>int</span> randomNumber =  (<span class='keyword'>int</span>)(fraction + aStart);    
    log(<span class='literal'>"Generated : "</span> + randomNumber);
  }
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> log(String aMessage){
    System.out.println(aMessage);
  }
} 
</PRE>
<br>
<br>An example run of this class :
<PRE>
Generating random integers in the range 1..10.
Generated : 9
Generated : 3
Generated : 3
Generated : 9
Generated : 4
Generated : 1
Generated : 3
Generated : 9
Generated : 10
Generated : 10
Done.
</PRE>


<p><b>Example 3</b>
<P>This example generates random floating point numbers in a Gaussian (normal) distribution. 
<br>
<PRE>

<span class='keyword'>import</span> java.util.Random;

<span class='comment'>/** 
Generate pseudo-random floating point values, with an 
approximately Gaussian (normal) distribution.

Many physical measurements have an approximately Gaussian 
distribution; this provides a way of simulating such values. 
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> RandomGaussian {
  
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main(String... aArgs){
    RandomGaussian gaussian = <span class='keyword'>new</span> RandomGaussian();
    <span class='keyword'>double</span> MEAN = <span class='literal'>100.0f</span>; 
    <span class='keyword'>double</span> VARIANCE = <span class='literal'>5.0f</span>;
    <span class='keyword'>for</span> (<span class='keyword'>int</span> idx = <span class='literal'>1</span>; idx <= <span class='literal'>10</span>; ++idx){
      log(<span class='literal'>"Generated : "</span> + gaussian.getGaussian(MEAN, VARIANCE));
    }
  }
    
  <span class='keyword'>private</span> Random fRandom = <span class='keyword'>new</span> Random();
  
  <span class='keyword'>private</span> <span class='keyword'>double</span> getGaussian(<span class='keyword'>double</span> aMean, <span class='keyword'>double</span> aVariance){
      <span class='keyword'>return</span> aMean + fRandom.nextGaussian() * aVariance;
  }

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> log(Object aMsg){
    System.out.println(String.valueOf(aMsg));
  }
} 
</PRE>
<br>
<br>An example run of this class :
<PRE>
Generated : 99.38221153454624
Generated : 100.95717075067498
Generated : 106.78740794978813
Generated : 105.57315286730545
Generated : 97.35077643206589
Generated : 92.56233774920052
Generated : 98.29311772993057
Generated : 102.04954815575822
Generated : 104.88458607780176
Generated : 97.11126014402141</PRE>


<br>
<br>

</div>





<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='62'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=62 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
